package com.example.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.cache.CaffineCache;
import com.example.dto.LoginDTO;
import com.example.model.SecUser;
import com.example.service.SecUserService;
import com.example.tools.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author liheng
 * @ClassName LoginController
 * @Description
 * @date 2020-08-20 17:24
 */
@Slf4j
@Api(tags = "登录 相关接口")
@RestController
@CrossOrigin
@RequestMapping("/")
public class LoginController {
    private final SecUserService secUserService;
    private final CaffineCache<String> accessTokenCache;

    @Autowired
    public LoginController(SecUserService secUserService, CaffineCache<String> accessTokenCache) {
        this.secUserService = secUserService;
        this.accessTokenCache = accessTokenCache;
    }

    /**
     * 登录接口
     */
    @ApiOperation("后台登录")
    @PostMapping(value = "login")
    public ApiResult login(@Validated @RequestBody LoginDTO loginDto) {
        String username = loginDto.getAccount();
        String password = loginDto.getPassword();
        SecUser user = secUserService.getOne(Wrappers.lambdaQuery(SecUser.class).eq(SecUser::getAccount, username).last(" LIMIT 1"));
        if (Objects.isNull(user)) {
            return ApiResult.failed("该用户不存在");
        } else if (password.equals(user.getPassword())) {
            String uuid = UUID.randomUUID().toString();
            accessTokenCache.setKey(uuid, username);
            Map<String,String> map = new HashMap<>(2);
            map.put("token",uuid);
            map.put("username",username);
            map.put("shortName",user.getShortName());
            return ApiResult.ok(map);
        }
        return ApiResult.failed("用户名或密码错误");
    }


    /**
     * 退出
     *
     * @return 退出登录
     */
    @ApiOperation("退出登录")
    @GetMapping("logout")
    public ApiResult<String> logout(@RequestHeader("token") String token) {
        boolean flag = accessTokenCache.delKey(token);
        if (flag) {
            return ApiResult.ok("退出成功");
        }
        return ApiResult.failed("退出失败");
    }

}
